<template>
  <Layout>
    <div class="login-container">
      <transition name="van-slide-right">
        <van-form
          v-show="aniFlag"
          autocomplete="off"
        >
          <center>
            <h1>Edums教学系统</h1>
          </center>
          <h2>用户登录</h2>
          <van-field
            v-model.trim="username"
            name="username"
            label="用户名"
            placeholder="输入用户名... "
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model.trim="password"
            type="password"
            name="password"
            label="密码"
            placeholder="输入密码..."
            :rules="[{ required: true, message: '请填写密码' }]"
          />

          <div style="margin: 16px;">
            <van-button
              round
              block
              color="#409eff"
              native-type="button"
              @click="doCaptchaBeforeLogin"
            >
              登录
            </van-button>
          </div>

          <Verify
            ref="captcha"
            captcha-type="blockPuzzle"
            @success="captchaSuccess"
          />
        </van-form>
      </transition>
    </div>
  </Layout>
</template>

<script>

import { Form, Field, Image, Toast } from 'vant'
import Verify from './verifition/Verify.vue'
import Layout from '@/views/layout'
import { encode } from '@/utils/encoder'

export default {
  name: 'Login',
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Image.name]: Image,
    Layout,
    Verify
  },
  data () {
    return {
      aniFlag: false, // 动画控制标识
      username: 'stu001',
      password: '123456',
      redirect: undefined
    }
  },
  computed: {},
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
        }
      },
      immediate: true
    }
  },
  created () {

  },
  mounted () {
    // 动画效果实现
    setInterval(() => {
      this.aniFlag = true
    }, 200)
  },
  methods: {
    doCaptchaBeforeLogin () { // 登录按钮点击响应
      // 显示验证码
      this.$refs.captcha.show()
    },
    captchaSuccess (captchaToken) { // 验证码验证成功回调
      const cToken = captchaToken.captchaVerification
      const reqData = {
        username: this.username,
        password: encode(this.password),
        sliderCaptcha: cToken
      }
      this.doLoginAction(reqData)
    },
    doLoginAction (reqData) { // 处理登录
      this.$store.dispatch('user/login', reqData).then(({ message }) => {
        Toast.success(message)
        if (this.redirect) {
          this.$router.replace({
            path: this.redirect
          })
        }
      }).catch(() => { })
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
}
.van-form {
  width: 100%;
}
</style>
